# import jusmargui
from PySide2.QtWidgets import (
    QApplication,
    QWidget,
    QTableWidgetItem,
    QTableWidget,
    QHeaderView,
    QAbstractItemView,
    QVBoxLayout,
    QTabWidget,
    QGroupBox,
    QLabel,
    QLineEdit,
    QHBoxLayout,
    QGridLayout,
    QComboBox,
    QPushButton,
    QListWidget,
    QDialog,
    QButtonGroup,
    QRadioButton,
    QCheckBox,
    QListWidgetItem,
    QMessageBox,
    QSizePolicy,
    QSpacerItem,
)
from PySide2.QtCore import Qt, Signal
from PySide2.QtGui import QPixmap, QDoubleValidator, QIntValidator, QImage, QMouseEvent
import sys
import csv
import os
import json
import subprocess
import copy
from gui.controls import envs
from datetime import datetime
from .. import message_box as MBox
from .. import config as Config
from ..utils import Utils
from ..dlg_model_params import DlgModeResetCls
from ..custom_widget import LineEditFloat, LineEditStr, SelectBox
from ..beam_and_mass_point.tank_select_node import DlgTankSelectNode


class DlgAddConnection(DlgModeResetCls):
    ok_signal = Signal(dict, str, int)

    def __init__(self, parent=None, params={}):
        super().__init__(parent)
        self.widgetDict = {}
        layout = QVBoxLayout()
        self.names = params.get("names") or []
        self.type = params.get("type") or "add"
        self.name = params.get("name") or ""
        self.index = params.get("index")
        self.setWindowTitle("创建连接" if self.type == "add" else "修改名称")
        if self.type == "add":
            self.paramsList = [
                {"name": "name", "type": "str", "title": "名称"},
                {
                    "name": "type",
                    "type": "select",
                    "title": "类型",
                    "options": [
                        {"value": "主捆绑", "title": "主捆绑"},
                        {"value": "rod", "title": "捆绑连杆"},
                    ],
                },
            ]
        else:
            self.paramsList = [{"name": "name", "type": "str", "title": "名称"}]
        gridLayout = QGridLayout()
        layout.addLayout(gridLayout)
        self.createParameterUI(self.paramsList, gridLayout)

        btnLayout = QHBoxLayout()
        btnLayout.setContentsMargins(-1, 10, -1, -1)
        cancelBtn = QPushButton("取消")
        okBtn = QPushButton("确定")

        btnLayout.setAlignment(Qt.AlignCenter)
        btnLayout.addWidget(okBtn)
        btnLayout.addWidget(cancelBtn)
        layout.addLayout(btnLayout)

        okBtn.clicked.connect(self.on_okBtn_clicked)
        cancelBtn.clicked.connect(self.close)

        self.setLayout(layout)

        if self.type != "add":
            self.widgetDict["name"].setValue(self.name)

    def on_okBtn_clicked(self):
        dict = {}
        for key, widget in self.widgetDict.items():
            value = widget.getValue()
            if value is None:
                MBox.warning("请填写完整信息！")
                return
            dict[key] = value
        if dict["name"] in self.names:
            MBox.warning("名称已存在！")
            return
        if self.type == "add":
            if dict["type"] == "主捆绑":
                dict["type"] = "main"
            else:
                dict["type"] = "rod"
        self.close()
        self.ok_signal.emit(dict, self.type, self.index)

    def createParameterUI(self, list, layout, row=0, col=0):
        for index, item in enumerate(list):
            name = item.get("name")
            index = row + index
            label = QLabel(item["title"])
            layout.addWidget(label, index, 0 + col)
            if item["type"] == "str":
                self.widgetDict[name] = LineEditStr()
            elif item["type"] == "float":
                self.widgetDict[name] = LineEditFloat()
            elif item["type"] == "select":
                self.widgetDict[name] = SelectBox(
                    options=item["options"], onChanged=item.get("onChanged")
                )
            layout.addWidget(self.widgetDict[name], index, 1 + col)
